package com.gelpag.business.common;

import com.gelpag.business.bean.Codelist;
import com.gelpag.business.exception.VueException;
import entity.Const;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tools.utils.Common;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//解决跨域问题,微服务之间调用时起作用，默认都加上
@CrossOrigin
@RestController
@RequestMapping(value = "/common")
public class CodelistController {

    @Autowired
    private CodelistService codelistService;

    /**
     * 获得codelist详情
     * @param codelist
     * @param request
     * @return
     */
    @PostMapping("/getCodelistByKind")
    public Result getCodelistByKind(Codelist codelist, HttpServletRequest request) {

        String token = request.getHeader("token");
        String code_kind = codelist.getCode_kind();

        //参数验证
        Map<String, String> checkMap = isPassGetCodelistByKind(code_kind);
        if (Const.NOT_NOMAL_PARAM.equals(checkMap.get(Const.PARAM_KEY))) {
            throw new VueException(Const.RESULT_1, checkMap.get(Const.PARAM_RET_KEY), token);
        }

        try {
            List<Codelist> codelists = codelistService.getCodelistByKind(code_kind);
            return new Result(Const.RESULT_0, "查询成功！", token, codelists);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Const.RESULT_1, "查询失败！", token, "");
        }
    }

    //参数验证
    private Map<String, String> isPassGetCodelistByKind(String code_kind) {

        Map<String, String> checkMap = new HashMap<>();
        //默认返回正常
        checkMap.put(Const.PARAM_KEY, Const.NOMAL_PARAM);
        if (Common.isNullString(code_kind)) {
            checkMap.put(Const.PARAM_KEY, Const.NOT_NOMAL_PARAM);
            checkMap.put(Const.PARAM_RET_KEY, "code_kind 必须填写！");
            return checkMap;
        }
        return checkMap;
    }
}
